﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ReporterEngine.Methods
{
    public class Dimensions : BaseMethod
    {
        public override bool IsUseable(LexPath.PathToken token)
        {
            return token.Kind == LexPath.TokenKind.Method && !string.IsNullOrEmpty(token.PathExp) && token.PathExp.ToLower() == "dimensions";
        }

        public override sQuery Execute(LexPath.PathToken token, sQuery query)
        {
            var result = query.New();

            foreach (var element in query.Elements)
            {
                if (element.Elements("dimensions").Count() > 0)
                {
                    foreach (var member in element.Element("dimensions").Elements("dimension"))
                    {
                        if (member.Attribute("refid") != null)
                        {
                            var refid = member.Attribute("refid").Value;

                            if (query._model.IDs.ContainsKey(refid))
                            {
                                var sourceEl = query._model.IDs[refid];

                                result.Elements.Add(sourceEl);
                            }
                        }
                    }
                }
            }

            result.Elements = result.Elements.Distinct(new CIFModel.NodeComparer()).ToList();

            result.Elements = result.Elements.OrderBy(x => query._model.GetElemenID(x, query)).ToList();

            return result;
        }

        public override MethodDescription[] GetMethodNames()
        {
            return new MethodDescription[]{new MethodDescription{Name = "dimensions"} };
        }
    }
}
